﻿using UnityEngine;
using System.Collections;

public class EnemyBehaviour : MonoBehaviour {

	public Transform meshEnemy;
	public float distanceToWalk = 6;
	public float speedWalk = 1;

	public int totalLife = 2;
	private int currentLife;

	public ParticleSystem explosionPower;

	private Vector3 rightDirection;
	private Vector3 leftDirection;
	private Vector3 startPosition;
	private Vector3 finalPosition;
	private bool inLeftDirection = true;
	private bool isBack = true;

	public float powerRate;
	private float currentPowerRate;

	public float distanceToAttack;
	public PowerBehaviour powerPrefab;
	private PlayerBehaviour player;
	public Transform bulletSpawnPoint;

	public bool canAttack;

	public AnimationClip attack;
	public AnimationClip walk;
	public AnimationClip destroy;
	public Animation enemyAnimations;

	// Use this for initialization
	void Start () {
		player = FindObjectOfType (typeof(PlayerBehaviour)) as PlayerBehaviour;

		startPosition = transform.position;
		finalPosition = startPosition;
		finalPosition.x -= distanceToWalk;

		leftDirection = transform.localScale;
		rightDirection = leftDirection;
		rightDirection.x *= -1;

		currentLife = totalLife;		

	}
	
	// Update is called once per frame
	void Update () {

		currentPowerRate += Time.deltaTime;

		if (inLeftDirection && isBack) {
			transform.Translate (Vector3.left * Time.deltaTime * speedWalk);
			transform.localScale = leftDirection;
			} 
		else {
			transform.Translate(Vector3.right * Time.deltaTime * speedWalk);
			transform.localScale = rightDirection;
		}

		if (transform.position.x > finalPosition.x) {
			inLeftDirection = true;
				}
		else {
			inLeftDirection = false;
			isBack = false;		
		}

		if (transform.position.x >	 startPosition.x) {
			isBack = true;		
		}

		float distanceToPlayer = Vector3.Distance (transform.position, player.transform.position);
		if (distanceToPlayer <= distanceToAttack && canAttack) {
			Attack();		
		}

		enemyAnimations.CrossFade (walk.name);
	}

	void OnTriggerEnter(Collider hit){
		if (hit.gameObject.tag == "Power") {
			currentLife--;		
			if(currentLife <= 0){
				Destroy(gameObject);
			}
			Instantiate(explosionPower.gameObject,hit.transform.position,hit.transform.rotation);
			Destroy(hit.gameObject);
		}
	}

	void Attack(){
		if(currentPowerRate >= powerRate){
			currentPowerRate = 0;
			GameObject projectil = Instantiate(powerPrefab.gameObject,bulletSpawnPoint.transform.position,bulletSpawnPoint.transform.rotation) as GameObject;
			projectil.GetComponent<PowerBehaviour>().right = !isBack;
			enemyAnimations.Play(attack.name);

		}
	}
	
}
